package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.MemberRaiOrder;
import com.ruoyi.system.domain.SysMember;
import com.ruoyi.system.domain.SysMemberRai;
import com.ruoyi.system.mapper.MemberRaiOrderMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysMemberMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysMemberRaiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 会员权益Controller
 * 
 * @author ruoyi
 * @date 2025-04-21
 */
@Api("会员权益")
@RestController
@RequestMapping("/system/rai")
public class SysMemberRaiController extends BaseController
{
    @Autowired
    private ISysMemberRaiService sysMemberRaiService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private MemberRaiOrderMapper memberRaiOrderMapper;
    @Autowired
    private SysMemberMapper sysMemberMapper;

    /**
     * 查询会员权益列表
     */
    @ApiOperation("查询会员权益列表")
    // @PreAuthorize("@ss.hasPermi('system:rai:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysMemberRai sysMemberRai)
    {
        startPage();
        // 两个上架的权益
        List<SysMemberRai> list = sysMemberRaiService.selectSysMemberRaiList(sysMemberRai);
        for (SysMemberRai sysMemberRai1 : list) {
            if (ObjectUtils.isNotEmpty(sysMemberRai1)){
                if(ObjectUtils.isNotEmpty(sysMemberRai1.getUpdateBy())){
                    Long aLong = Long.parseLong(sysMemberRai1.getUpdateBy());
                    SysUser sysUser = sysUserMapper.selectUserById(aLong);
                    sysMemberRai1.setUpdateByName(sysUser.getUserName());
                }
                MemberRaiOrder param = new MemberRaiOrder();
                param.setRaiId(sysMemberRai1.getId());
                List<MemberRaiOrder> memberRaiOrders = memberRaiOrderMapper.selectMemberRaiOrderList(param);
                // 判断是否可以领取权益
                if (ObjectUtils.isEmpty(memberRaiOrders)){
                    sysMemberRai1.setGetStatus("0");
                }else{
                    // 获取间隔天数
                    int intervalNum = Integer.parseInt(sysMemberRai1.getIntervalNum());
                    Date createTime = memberRaiOrders.get(0).getCreateTime();
                    // 使用 Calendar 计算未来时间
                    // 获取未来的时间
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(createTime);
                    calendar.add(Calendar.DATE, intervalNum); // 加上间隔天数
                    Date futureTime = calendar.getTime();
                    // 获取当前时间
                    Date now = new Date();
                    if (now.after(futureTime)){
                        sysMemberRai1.setGetStatus("0");
                    }else{
                        sysMemberRai1.setGetStatus("1");
                    }
                }
            }
        }
        return getDataTable(list);
    }

    @ApiOperation("查询会员权益列表")
    // @PreAuthorize("@ss.hasPermi('system:rai:list')")
    @PostMapping("/listHf")
    @Anonymous
    public TableDataInfo listH5(@RequestBody SysMemberRai sysMemberRai)
    {
        String phonenumber = sysMemberRai.getPhonenumber();
        if (ObjectUtils.isNotEmpty(phonenumber)){
            SysMember sysMember = sysMemberMapper.selectSysMemberByPhone(phonenumber);
            if (ObjectUtils.isNotEmpty(sysMember) && "0".equals(sysMember.getStatus())){
                return new TableDataInfo(null, 0);
            }
        }
        SysMember sysMember = sysMemberMapper.selectSysMemberByPhone(phonenumber);
        startPage();
        // 两个上架的权益
        List<SysMemberRai> list = sysMemberRaiService.selectSysMemberRaiList(sysMemberRai);
        for (SysMemberRai sysMemberRai1 : list) {
            if (ObjectUtils.isNotEmpty(sysMemberRai1)){
                if(ObjectUtils.isNotEmpty(sysMemberRai1.getUpdateBy())){
                    Long aLong = Long.parseLong(sysMemberRai1.getUpdateBy());
                    SysUser sysUser = sysUserMapper.selectUserById(aLong);
                    sysMemberRai1.setUpdateByName(sysUser.getUserName());
                }
                MemberRaiOrder param = new MemberRaiOrder();
                param.setRaiId(sysMemberRai1.getId());
                param.setMemberId(sysMember.getId());
                List<MemberRaiOrder> memberRaiOrders = memberRaiOrderMapper.selectMemberRaiOrderList(param);
                // 判断是否可以领取权益
                if (ObjectUtils.isEmpty(memberRaiOrders)){
                    sysMemberRai1.setGetStatus("0");
                }else{
                    // 先判断领取次数
                    int intervalNum = Integer.parseInt(sysMemberRai1.getIntervalNum());
                    if (intervalNum > memberRaiOrders.size()){
                        // 获取间隔天数
                        Date createTime = memberRaiOrders.get(0).getCreateTime();
                        // 使用 Calendar 计算未来时间
                        // 获取未来的时间
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(createTime);
                        calendar.add(Calendar.DATE, intervalNum); // 加上间隔天数
                        Date futureTime = calendar.getTime();
                        // 获取当前时间
                        Date now = new Date();
                        if (now.after(futureTime)){
                            sysMemberRai1.setGetStatus("0");
                        }else{
                            sysMemberRai1.setGetStatus("1");
                        }
                    }else{
                        sysMemberRai1.setGetStatus("1");
                    }

                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出会员权益列表
     */
    @ApiOperation("导出会员权益列表")
    // @PreAuthorize("@ss.hasPermi('system:rai:export')")
    @Log(title = "会员权益", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysMemberRai sysMemberRai)
    {
        List<SysMemberRai> list = sysMemberRaiService.selectSysMemberRaiList(sysMemberRai);
        ExcelUtil<SysMemberRai> util = new ExcelUtil<SysMemberRai>(SysMemberRai.class);
        util.exportExcel(response, list, "会员权益数据");
    }

    /**
     * 获取会员权益详细信息
     */
    @ApiOperation("获取会员权益详细信息")
    // @PreAuthorize("@ss.hasPermi('system:rai:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(sysMemberRaiService.selectSysMemberRaiById(id));
    }

    /**
     * 新增会员权益
     */
    @ApiOperation("新增会员权益")
    // @PreAuthorize("@ss.hasPermi('system:rai:add')")
    @Log(title = "会员权益", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysMemberRai sysMemberRai)
    {
        return toAjax(sysMemberRaiService.insertSysMemberRai(sysMemberRai));
    }

    /**
     * 修改会员权益
     */
    @ApiOperation("修改会员权益")
    // @PreAuthorize("@ss.hasPermi('system:rai:edit')")
    @Log(title = "会员权益", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysMemberRai sysMemberRai)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        sysMemberRai.setUpdateBy(user.getUserId() + "");
        return toAjax(sysMemberRaiService.updateSysMemberRai(sysMemberRai));
    }

    /**
     * 删除会员权益
     */
    @ApiOperation("删除会员权益")
    // @PreAuthorize("@ss.hasPermi('system:rai:remove')")
    @Log(title = "会员权益", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(sysMemberRaiService.deleteSysMemberRaiByIds(ids));
    }
}
